using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using NHibernate;
using Iesi.Collections.Generic;
using System.IO;
using TanashCMS.Business.DTO;

namespace TanashCMS.Business
{
    [DataObject(true)]
    public class TanashWebsite
    {
        private int mID;
        private int mHomePageID;
        private string mTitle;
        private string mHostHeader;
        private string mURL;
        private bool mOnline, mNeedsPublish=false;
        private TanashCMS.Business.CMSObjectState mState;
        private string mSubFolderName;
        [System.Xml.Serialization.SoapIgnore(), System.Xml.Serialization.XmlIgnore()]
        private TanashCustomer mCustomer = null;
        private int mCustomerID = 0;
        private int differenceFromGMT=12;
        private string mDefaultTemplate = "default";

        public virtual int CustomerID { get { return mCustomerID; } set { mCustomerID = value; } }
        [System.Xml.Serialization.SoapIgnore(), System.Xml.Serialization.XmlIgnore()]
        public virtual TanashCustomer Customer { get { return mCustomer; } set { mCustomer = value; } }
        public virtual bool NeedsPublish { get { return mNeedsPublish; } set { mNeedsPublish = value; } }

        public virtual string DefaultTemplate { get { return mDefaultTemplate; } set { mDefaultTemplate = value; } }

        public virtual int ID
        {
            get
            {
                return mID;
            }
            set
            {
                mID = value;
            }
        }

        public virtual int DifferenceFromGMT
        {
            get { return differenceFromGMT; }
            set { differenceFromGMT = value; }
        }


        public virtual string Title
        {
            get
            {
                return mTitle;
            }
            set
            {
                mTitle = value;
            }
        }

        public virtual int HomePageID
        {
            get
            {
                return mHomePageID;
            }
            set
            {
                mHomePageID = value;
            }
        }

        public virtual string URL
        {
            get
            {
                return mURL;
            }
            set
            {
                mURL = value;
            }
        }

        public virtual string HostHeader
        {
            get
            {
                return mHostHeader;
            }
            set
            {
                mHostHeader = value;
            }
        }

        public virtual bool IsOnline
        {
            get
            {
                return mOnline;
            }
            set
            {
                mOnline = value;
            }
        }

        public virtual CMSObjectState State
        {
            get
            {
                return mState;
            }
            set
            {
                mState = value;
            }
        }

        /// <summary>
        /// The text value to use when specifying a sub-folder on the subdirectory e.g: /UserImages/[SubFolder]/
        /// </summary>
        public virtual string SubFolderName
        {
            get { return mSubFolderName; }
            set { mSubFolderName = value; }
        }

        public virtual string getOptionValue(string OptionTitle)
        {
            WebsiteOption option = (WebsiteOption)Configuration.GetCurrentSession().CreateQuery("select o from WebsiteOption o where o.WebsiteID = " + this.mID.ToString() + " and o.OptionTitle = '" + OptionTitle + "'").UniqueResult();

            if (option != null)
                return option.OptionValue;
            
            return "";
        }
        public virtual WebsiteOption getOption(string OptionTitle)
        {
            return (WebsiteOption)Configuration.GetCurrentSession().CreateQuery("select o from WebsiteOption o where o.WebsiteID = " + this.mID.ToString() + " and o.OptionTitle = '" + OptionTitle + "'").UniqueResult();
        }

        public static List<TanashWebsite> List()
        {
            ISession session = Configuration.GetCurrentSession();
            List<TanashWebsite> websites = (List<TanashWebsite>)session.CreateQuery("select website from TanashWebsite website order by website.Customer.Name, website.Title").List<TanashWebsite>();
            session.Disconnect();
            return websites;
        }

        public static List<TanashWebsite> List(int CustomerID)
        {
            ISession session = Configuration.GetCurrentSession();
            List<TanashWebsite> websites = null;
            if (CustomerID != 0)
                websites =  (List<TanashWebsite>)session.CreateQuery("select website from TanashWebsite website where website.Customer.ID = " + CustomerID.ToString() + " order by Title").List<TanashWebsite>();
            else
                websites = (List<TanashWebsite>)session.CreateQuery("select website from TanashWebsite website order by Title").List<TanashWebsite>();
            session.Disconnect();
            return websites;
        }

        public static TanashWebsite GetByHostName(string HostName)
        {
            if (HostName.Substring(0, 4) == "www.")
                HostName = HostName.Substring(4);

            ISession session = Configuration.GetCurrentSession();
            return (TanashWebsite)session.CreateQuery("select w from TanashWebsite w where w.HostHeader like '%" + HostName + "%'").SetMaxResults(1).SetFirstResult(0).UniqueResult();
        }

        public static void Update(TanashWebsite Website)
        {
            ISession session = Configuration.GetCurrentSession();
            ITransaction tx = session.BeginTransaction();

            TanashWebsite webCopy = session.Get<TanashWebsite>(Website.ID);
            webCopy.HomePageID = Website.HomePageID;
            webCopy.HostHeader = Website.HostHeader;
            webCopy.IsOnline = Website.IsOnline;
            webCopy.State = Website.State;
            webCopy.SubFolderName = Website.SubFolderName;
            webCopy.Title = Website.Title;
            webCopy.URL = Website.URL;

            //webCopy.Customer = Configuration.GetCurrentSession().Get<TanashCustomer>(Website.CustomerID);

            try
            {
                session.SaveOrUpdate(webCopy);
                session.Flush();
                tx.Commit();
                session.Disconnect();
            }
            catch (Exception ex)
            {
                tx.Rollback();
                session.Disconnect();
                throw ex;
            }
        }
        public static void Insert(TanashWebsite Website)
        {
            Website.Customer = Configuration.GetCurrentSession().Get<TanashCustomer>(Website.CustomerID);
            Configuration.GetCurrentSession().Save(Website);
        }
        public static void Delete(TanashWebsite Website)
        {
            ISession session = Configuration.GetCurrentSession();
            ITransaction tx = session.BeginTransaction();

            TanashWebsite originalWebsite = session.Get<TanashWebsite>(Website.ID);
            
            try
            {
                session.Delete(originalWebsite);
                tx.Commit();
                session.Flush();
                session.Disconnect();
            }
            catch (Exception ex)
            {
                tx.Rollback();
                session.Disconnect();
                throw ex;
            }
        }

        public string WebsiteFolder
        {
            get
            {
                return string.Format("/CustomAssets/{0}", this.mSubFolderName);
            }
        }
        public string TemplatesFolder
        {
            get
            {
                return string.Format("{0}/templates", WebsiteFolder);
            }
        }
        public string ImagesFolder
        {
            get
            {
                return string.Format("{0}/image", WebsiteFolder);
            }
        }
        public string ImportFolder
        {
            get
            {
                return string.Format("{0}/import", WebsiteFolder);
            }
        }
        public string TempFolder
        {
            get
            {
                return string.Format("{0}/temp", WebsiteFolder);
            }
        }
        public string XmlPath
        {
            get
            {
                return string.Format("{0}/{1}.xml", WebsiteFolder, mSubFolderName);
            }
        }
        public string ImagesXmlPath
        {
            get
            {
                return string.Format("{0}/{1}.images.xml", WebsiteFolder, mSubFolderName);
            }
        }

        public WebpageTemplate[] GetTemplates()
        {
            List<WebpageTemplate> templates = new List<WebpageTemplate>();
            DirectoryInfo folder = new DirectoryInfo(Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, TemplatesFolder.TrimStart('/')));
            if (!folder.Exists) return templates.ToArray();

            DirectoryInfo[] templateFolders = folder.GetDirectories();
            foreach (DirectoryInfo templateFolder in templateFolders)
            {
                if (File.Exists(Path.Combine(templateFolder.FullName, "template.xsl")))
                {
                    templates.Add(new WebpageTemplate(templateFolder.Name, Path.Combine(templateFolder.FullName, "template.xsl")));
                }
            }

            return templates.ToArray();

        }


    }
}
